package com.example.wendao.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.PagedList;

import com.example.wendao.common.AsyncExecutor;
import com.example.wendao.common.PageUtils;
import com.example.wendao.model.entity.Goods;
import com.example.wendao.model.service.GoodsService;


/**
 * 封装了商品操作和数据的ViewModel
 */
public class  GoodsViewModel extends ViewModel {

    private GoodsService goodsService;

    private LiveData<PagedList<Goods>> allGoods;

    {
        goodsService = new GoodsService();

        allGoods = new PageUtils<Goods>().buildLivePagedList(goodsService.findAllGoods());
    }

    /**
     * 根据商品ID查询到指定商品
     * @param goodId    商品ID
     * @return          查询到的商品对象
     */
    public Goods getGoodById(int goodId){
        return new AsyncExecutor<Goods>().submit(() -> goodsService.findGoodById(goodId));
    }


    /**
     * 获取到所有的商品列表
     * @return  所有的商品
     */
    public LiveData<PagedList<Goods>> getAllGoods(){
        return allGoods;
    }

    /**
     * 根据商品ID删除商品
     * @param goodId    商品ID
     */
    public void deleteGoodById(int goodId){
        new AsyncExecutor<>().execute(() -> goodsService.deleteGoodById(goodId));
    }

    /**
     * 删除商品
     * @param good  要删除的商品
     */
    public void deleteGood(Goods... good){
        new AsyncExecutor<>().execute(() -> goodsService.deleteGood(good));
    }

    /**
     * 添加一个商品
     * @param goods 要添加的商品
     */
    public void addGoods(Goods... goods){
        new AsyncExecutor<>().execute(() -> goodsService.insertGoods(goods));
    }

    /**
     * 更新一个商品
     * @param goods 要更新的商品
     */
    public void updateGood(Goods goods){
        new AsyncExecutor<>().execute(() -> goodsService.updateGood(goods));
    }

}
